package com.keller.service.impl;

import com.keller.dao.UserDao;
import com.keller.domian.Role;
import com.keller.domian.UserInfo;
import com.keller.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao userDao;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    @Override
    public void saveUser(UserInfo userInfo) {
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        System.out.println(userInfo.getPassword());
        userDao.saveUser(userInfo);
    }

    //根据用户id查询用户详情
    @Override
    public UserInfo findUserDetailByUserId(String userId) {
        return userDao.findUserDetailByUserId(userId);
    }

    //根据id查询用户未拥有的权限
    @Override
    public List<Role> findOtherRoleById(String id) {
        return userDao.findOtherRoleById(id);
    }

    //根据用户id及角色id添加到users_role表中
    @Override
    public void addRoleToUser(String userId, String[] ids) {
        for(String roleId : ids){
            userDao.addRoleToUser(userId,roleId);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findUserByUsername(username);
        //把自己的用户对象封装在user对象中返回，user实现了userDetail接口
        User user = new User(userInfo.getUsername(), userInfo.getPassword(), getAuthorities(userInfo.getRoles()));
        return user;
    }

    public List<SimpleGrantedAuthority> getAuthorities(List<Role> roles){
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for(Role role : roles){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }
}
